<?php
include_once("class.groups.php");
include_once("class.logs.php");
include_once("class.users.php");
include_once("class.persons.php");
include_once("class.notes.php");
require_once("class.phpmailer.php");
require_once("class.files.php");
require_once("class.categories.php");

//sessions variable definition
define('svar','ibnbd_user');
define('tblPrefix','ibnbd_');
define('logFilePath','logs');
define('logFile','system.log');
class_alias('IBNBD','MAIN');

class IBNBD{
	
	public $currentUser;
	
	public $groups;
	public $logs;
	public $users;
	public $persons;
	public $notes;
	public $files;
	public $categories;	
		
	var $dbErrorMsg = "Failed retreiving data from database: ";

	function __construct(){
		$server = "localhost"; 	//SERVER: localhost
		$db = "ibnrushd_eu";			//SERVER: offthered_com
		$dbu = "ibnrushd_eu";			//SERVER: offthered_com
		$dbp = "HWfVHLcC";				//SERVER: secret
		mysql_connect($server, $dbu, $dbp) or die("Failed connecting to server ".$server);
		mysql_select_db($db) or die("Failed selecting database: ".$db);
		if (!isset ($_COOKIE[ini_get('session.name')])) {
			session_start();
		}
		
		$this->groups = new GROUPS();
		$this->logs = new LOGS(logFilePath."\\".logFile);
		$this->users=new USERS();
		$this->persons=new PERSONS();
		$this->notes=new NOTES();
		$this->files=new FILES();
		$this->categories=new CATEGORIES();
		if($this->users->checkLogin(false)){
			$this->currentUser = $this->users->getUser(-1);
		}				
	}
	
	public function executeCommand($query){
		return mysql_query($query) or die($this->dbErrorMsg.$query." Mysql : ".mysql_error());
	}
	
	//general database queries
	public function returnArray($query){
		$data = array();
		$res = mysql_query($query) or die($this->dbErrorMsg.$query." Mysql : ".mysql_error());
		while($row=mysql_fetch_assoc($res)){
			array_push($data, $row);
		}
		return $data;
	}

	public function returnRow($query){
		$res = mysql_query($query) or die($this->dbErrorMsg.$query." Mysql : ".mysql_error());
		$row=mysql_fetch_assoc($res);
		return $row;
	}
	/** Function Check if is a valid email
	 * @param : string $email
	 * @return : boolean is vaild or not
	 */
	function validEmail($email){
	   $isValid = true;
	   $atIndex = strrpos($email, "@");
	   if (is_bool($atIndex) && !$atIndex){
	      $isValid = false;
	   }else{
	      $domain = substr($email, $atIndex+1);
	      $local = substr($email, 0, $atIndex);
	      $localLen = strlen($local);
	      $domainLen = strlen($domain);
	      if ($localLen < 1 || $localLen > 64){// local part length exceeded
	         $isValid = false;
	      }else if ($domainLen < 1 || $domainLen > 255){// domain part length exceeded
	         $isValid = false;
	      }else if ($local[0] == '.' || $local[$localLen-1] == '.'){// local part starts or ends with '.'
	         $isValid = false;
	      }else if (preg_match('/\\.\\./', $local)){// local part has two consecutive dots
	         $isValid = false;
	      }else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)){// character not valid in domain part
	         $isValid = false;
	      }else if (preg_match('/\\.\\./', $domain)){// domain part has two consecutive dots
	         $isValid = false;
	      }else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))){// character not valid in local part unless local part is quoted
	         if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))){
	            $isValid = false;
	         }
	      }
	   }
	   return $isValid;
	}
	/** Function for encode a string (IBN way)
	 * return : encoded string
	 */
	function encode($string){
		//if(intval($string))($string = dechex($string));
        //$string = dechex($string);
	    $encodedStr = $string;
	    $num = mt_rand(1,5);
	    for($i=1;$i<=$num;$i++){
		    $encodedStr = base64_encode($encodedStr);
	    }
	    $seed_array = array('S','H','A','F','I','Q');
	    $encodedStr = $encodedStr . "+" . $seed_array[$num];
	    $encodedStr = base64_encode($encodedStr);
	    return $encodedStr;
	}
	/** Function for decoding a string
	 * return : decoded string
	 */
	function decode($string, $return = 'xxx'){
	    $seed_array = array('S','H','A','F','I','Q');
	    $decoded =  base64_decode($string);
	    list($decoded,$letter) =  @split("\+",$decoded);
	    for($i=0;$i<count($seed_array);$i++){
	      if($seed_array[$i] == $letter)
	      break;
	    }
	    for($j=1;$j<=$i;$j++){
	     $decoded = base64_decode($decoded);
	    }
		if($return=='int'){
		    return hexdec($decoded);		
		}else{
	    	return $decoded;
		}
	}
	/** Function for detecting internet explorer
	 * return : boolean (true)if internet explorer
	 */
	function isIE(){
	    if (isset($_SERVER['HTTP_USER_AGENT'])&& (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false)){
	        return true;
		}else{
	        return false;
		}
	}
	/** Function for getting the real client IP address regardless of proxy
     * @return real client IP address
     */
    function getIP(){
        //check ip from share internet
		if (!empty($_SERVER['HTTP_CLIENT_IP'])){
			$ip=$_SERVER['HTTP_CLIENT_IP'];
		}
		//to check ip is pass from proxy
		elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
			$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
		} else {
			$ip=$_SERVER['REMOTE_ADDR'];
		}
		return $ip;
    }
	/**
	 * Function general for returning a remote content
	 * return: string content
	 */
    function curl_get($url) {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        $return = curl_exec($curl);
        curl_close($curl);
        return $return;
    }
	
    function isAjax() {
        return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'));
    }
    function isLink($url){
        return preg_match("/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i",$url);
    }
	/**
     * function for stripping the content of a text (shorting)
     * return : string 
     */
    function stringLength($string, $length){
    	$string = strip_tags($string);
    	if (strlen($string) >= $length){
    		$string = substr($string, 0, strrpos(substr($string, 0, $length), ' '));      		
    	}
    	return $string;
    }
    /**
     * function to make string Camelcase
     * return: string
     */
	function strtoCamelCase($str){
		if(strlen($str)>0){
			$str[0] = strtoupper($str[0]);
		}
		return $str;
	}
	/**
	 * function for stripping break lines(<br/>)
	 * return: string 
	 */
	function br2nl($text){
		return  preg_replace('/<br\\s*?\/??>/i', '', $text);
	}
	function highlightWords($string, $words){
		foreach($words as $word){
			$string = str_ireplace($word, '<span class="highlight_word">'.$word.'</span>', $string);
		}
		return $string;
	}
	function forceUTF8($text){
		if(is_array($text)){
	      foreach($text as $k => $v){
	      	$text[$k] = YKB::forceUTF8($v);
	      }
	      return $text;
		}
		$max = strlen($text);
		$buf = "";
		for($i = 0; $i < $max; $i++){
			$c1 = $text{$i};
			if($c1>="\xc0"){ //Should be converted to UTF8, if it's not UTF8 already
				$c2 = $i+1 >= $max? "\x00" : $text{$i+1};
				$c3 = $i+2 >= $max? "\x00" : $text{$i+2};
				$c4 = $i+3 >= $max? "\x00" : $text{$i+3};
				if($c1 >= "\xc0" & $c1 <= "\xdf"){ //looks like 2 bytes UTF8
					if($c2 >= "\x80" && $c2 <= "\xbf"){ //yeah, almost sure it's UTF8 already
						$buf .= $c1 . $c2;
						$i++;
					}else{ //not valid UTF8.  Convert it.
						$cc1 = (chr(ord($c1) / 64) | "\xc0");
						$cc2 = ($c1 & "\x3f") | "\x80";
						$buf .= $cc1 . $cc2;
					}
				}elseif($c1 >= "\xe0" & $c1 <= "\xef"){ //looks like 3 bytes UTF8
					if($c2 >= "\x80" && $c2 <= "\xbf" && $c3 >= "\x80" && $c3 <= "\xbf"){ //yeah, almost sure it's UTF8 already
						$buf .= $c1 . $c2 . $c3;
						$i = $i + 2;
					}else{ //not valid UTF8.  Convert it.
						$cc1 = (chr(ord($c1) / 64) | "\xc0");
						$cc2 = ($c1 & "\x3f") | "\x80";
						$buf .= $cc1 . $cc2;
					}
	            }elseif($c1 >= "\xf0" & $c1 <= "\xf7"){ //looks like 4 bytes UTF8
	            	if($c2 >= "\x80" && $c2 <= "\xbf" && $c3 >= "\x80" && $c3 <= "\xbf" && $c4 >= "\x80" && $c4 <= "\xbf"){ //yeah, almost sure it's UTF8 already
	            		$buf .= $c1 . $c2 . $c3;
	            		$i = $i + 2;
	            	}else{ //not valid UTF8.  Convert it.
	            		$cc1 = (chr(ord($c1) / 64) | "\xc0");
	            		$cc2 = ($c1 & "\x3f") | "\x80";
	            		$buf .= $cc1 . $cc2;
	            	}
	            }else{ //doesn't look like UTF8, but should be converted
	            	$cc1 = (chr(ord($c1) / 64) | "\xc0");
	            	$cc2 = (($c1 & "\x3f") | "\x80");
	            	$buf .= $cc1 . $cc2;
	            }
			}elseif(($c1 & "\xc0") == "\x80"){ // needs conversion
				$cc1 = (chr(ord($c1) / 64) | "\xc0");
				$cc2 = (($c1 & "\x3f") | "\x80");
				$buf .= $cc1 . $cc2;
			}else{ // it doesn't need convesion
				$buf .= $c1;
			}
		}
		return $buf;
	}
    /**
     * Sent email - IMPORTANT !!!! -> SET PARAMS in function
     * @param string $to
     * @param string $subject
     * @param string $message
     * @param string $from
     * @return boolean
     */
    function sendMail($to, $subject, $message, $debug=1){
    	/*
    	 * mo1.b-one.net
    	 */
        $mailobj = new PHPMAILER();
		$mailobj->isSMTP();
        $mailobj->IsHTML(true);
        $mailobj->AddAddress($to);
        $mailobj->From        	= "info@ontheblue.se";
        $mailobj->FromName    	= "on the blue | contact"; //
        //$mailobj->Port        	= 2525; //
        $mailobj->Mailer    	= "smtp";
        $mailobj->Subject   	= $subject;
        $mailobj->Body        	= $message;
        $mailobj->SMTPAuth    	= false;
        //SET THOSE PARAMS!!!
        $mailobj->Host        	= "mo1.b-one.net";//
        $mailobj->Username    	= "info@ontheblue.se";
        $mailobj->Password    	= "padureaverde";
        $mailobj->SMTPDebug    	= $debug;
        if(!$mailobj->Send()){
            //echo "Failed composing/sending message";
            return false;
        }else{
            //$this->logIt('mail',$to);
            //echo "An email has been sent to:<br />$email<br />";
            return true;
        }
    }

}
?>